import { createStore,createLogger } from 'vuex'
import staff from './staff'
import device from './device'
const myPlugin = (store) => {
  // 当 store 初始化后调用
  store.subscribe((mutation, state) => {
    sessionStorage.setItem('vuexState',JSON.stringify(state))
    // 每次 mutation 之后调用
    // mutation 的格式为 { type, payload }
  })
}
var vuexState = null;
if (sessionStorage.getItem('vuexState')) {
  vuexState = JSON.parse(sessionStorage.getItem('vuexState'))
}

const store = createStore({
  // 严格模式下，无论何时发生了状态变更且不是由 mutation 函数引起的，将会抛出错误
  strict: process.env.NODE_ENV !== 'production',
  modules: {
    staff,
    device
  },
  state () {
    return vuexState?vuexState: {
      count: 0,
      deviceList: [
        {name: '洗衣机',price: 600},
        {name: '电视机',price: 2600},
        {name: '油烟机',price: 1600},
      ]
    }
  },
  getters: {
    totalPrice(state){
      return state.deviceList.reduce((sum,item)=>{
        return sum + item.price
      },0)
    }
  },
  mutations: {
    plus (state,val=1) {
      state.count += val
    },
    reduce (state) {
      state.count--
    },
    countChange (state,val) {
      state.count = val;
    }
  },
  actions: {
    asyncPlus (context,val) {
      return new Promise((res,rej)=>{
        setTimeout(function () {
          context.commit('plus',val)
          res()
        },1000)
      })
    }
  },
  plugins: [myPlugin,createLogger()]
})
export default function (app) {
  app.use(store)
}